//
//  OPBApnsHelper.swift
//  newPush
//
//  Created by zz on 21.3.24.
//

import UIKit
import AVFoundation

private let GroupName = "group.opay.ng"
class OPBApnsHelper: NSObject {
    public static let shared = OPBApnsHelper()
    // 要挪动的文件记录
    let voiceSource = ["user_payment.mp3",
                       "0.mp3",
                       "1.mp3",
                       "2.mp3",
                       "3.mp3",
                       "4.mp3",
                       "5.mp3",
                       "6.mp3",
                       "7.mp3",
                       "8.mp3",
                       "9.mp3",
                       "百.mp3",
                       "点.mp3",
                       "千.mp3",
                       "十.mp3",
                       "万.mp3",
                       "元.mp3",
                       "money.mp3"
    ]
    
    let targetPath = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: GroupName)!.absoluteString.replacingOccurrences(of: "file://", with: "") + "Library/Sounds/"
    
    
    func getMusicArray(with numStr: String) -> [String] {
        guard let finalStr = makeMusicFrom(numStr) else {
            return []
        }
        // 前部分字段例如:***到账 user_payment是项目自定义的音乐文件
        var finalArr = ["user_payment"]
        
        for char in finalStr {
            finalArr.append(String(char))
        }
        return finalArr
    }
    

    
    func makeMusicFrom(_ numstr: String) -> String? {
        let numberchar = ["0","1","2","3","4","5","6","7","8","9"]
        let inunitchar = ["","十","百","千"]
        let unitname = ["","万","亿"]
        
        let valstr = String(format: "%.2f", Double(numstr) ?? 0.00)
        
        var prefix = ""
        
        let head = String(valstr.prefix(valstr.count - 2 - 1))
        let foot = String(valstr.suffix(2))
        
        if head == "0" {
            prefix = "0"
        } else {
            var ch = [String]()
            for char in head {
                ch.append(String(format: "%x", char.asciiValue! - UInt8(ascii: "0")))
            }
            
            var zeronum = 0
            for i in 0..<ch.count {
                let index = (ch.count - 1 - i) % 4
                let indexloc = (ch.count - 1 - i) / 4
                
                if ch[i] == "0" {
                    zeronum += 1
                } else {
                    if zeronum != 0 {
                        if index != 3 {
                            prefix += "零"
                        }
                        zeronum = 0
                    }
                    if ch.count > i {
                        if let numIndex = Int(ch[i]), numIndex < numberchar.count {
                            prefix += numberchar[numIndex]
                        }
                    }
                    
                    if inunitchar.count > index {
                        prefix += inunitchar[index]
                    }
                }
                if index == 0 && zeronum < 4 {
                    if unitname.count > indexloc {
                        prefix += unitname[indexloc]
                    }
                }
            }
        }
        
        if prefix.hasPrefix("1十") {
            prefix = prefix.replacingOccurrences(of: "1十", with: "十")
        }
        
        if foot == "00" {
            prefix += "元"
        } else {
            prefix += String(format: "点%@元", foot)
        }
        
        return prefix
    }
    
    /// 合并音频文件
    /// - Parameters:
    ///   - musicArry: ["1","百","零","6"]
    ///   - completed: 合成后的文件名称
    func mergeVoiceAudiFileName(musicArry:[String],completed:((String?)->Void)?) {
        clear(targetPath)
        
        let composition = AVMutableComposition()
        var beginTime = CMTime.zero
        
        for audioFileName in musicArry {
            if let audioFilePath = Bundle.main.path(forResource: audioFileName, ofType: "mp3") {
                guard let audioAsset = AVURLAsset(url: URL(fileURLWithPath: audioFilePath)) as AVURLAsset?,
                      let audioAssetTrack = audioAsset.tracks(withMediaType: AVMediaType.audio).first else {
                    continue
                }
                let audioTrack = composition.addMutableTrack(withMediaType: AVMediaType.audio, preferredTrackID: kCMPersistentTrackID_Invalid)
                
                do {
                    try audioTrack?.insertTimeRange(CMTimeRange(start: .zero, duration: audioAsset.duration), of: audioAssetTrack, at: beginTime)
                    beginTime = CMTimeAdd(beginTime, audioAsset.duration)
                } catch {
                    print("Failed to insert audio track: \(error)")
                    return
                }
            }
        }
        
        if !FileManager.default.fileExists(atPath: targetPath) {
            do {
                try FileManager.default.createDirectory(atPath: targetPath, withIntermediateDirectories: true, attributes: nil)
            } catch {
                NSLog("创建Sounds文件失败 \(targetPath)")
            }
        }
        
        let fileName = "\(now()).m4a"
        let fileUrl = URL(string: "file://\(targetPath)\(fileName)")
        guard let url = fileUrl else { return }
        
        let session = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetAppleM4A)
        let outPutFilePath = url
        
        session?.outputURL = outPutFilePath
        session?.outputFileType = AVFileType.m4a
        session?.shouldOptimizeForNetworkUse = true
        
        session?.exportAsynchronously {
            if session?.status == AVAssetExportSession.Status.completed {
                print("合并成功----\(outPutFilePath)")
                completed?(fileName)
            } else {
                print("合并失败")
                completed?(nil)
            }
        }
    }
    
    
    
    func mergeVoice(musicArry:[String]) -> String {
        clear(targetPath)
        var mergeData = Data()
        // 1: 遍历要挪动的文件源
        musicArry.forEach { fileName in
            if let filePath = Bundle.main.path(forResource: fileName, ofType: "mp3") {
                let contentUrl = URL(fileURLWithPath: filePath)
                if let data = try? Data(contentsOf: contentUrl) {
                    mergeData.append(data)
                }
            }
        }
        guard !mergeData.isEmpty else { return "" }
        if !FileManager.default.fileExists(atPath: targetPath) {
            do {
                try FileManager.default.createDirectory(atPath: targetPath, withIntermediateDirectories: true, attributes: nil)
            } catch {
                NSLog("创建Sounds文件失败 \(targetPath)")
            }
        }
        let fileName = "\(now()).mp3"
        let fileUrl = URL(string: "file://\(targetPath)\(fileName)")
        guard let url = fileUrl else { return "" }
        do {
            try mergeData.write(to: url)
        } catch {
            NSLog("合成mp3文件失败 \(url)")
        }
        return fileName
    }

    
    
    private func clear(_ libPath: String) {
      var isDir: ObjCBool = false
      guard FileManager.default.fileExists(atPath: libPath, isDirectory: &isDir), let list = try? FileManager.default.contentsOfDirectory(atPath: libPath) else { return }
      let before = now() - 12*60*60*1000 //1day ago
      list.forEach { file in
        if let time = Int(file.replacingOccurrences(of: ".mp3", with: "")), time < before {
          
            //delete file
          do {
            try FileManager.default.removeItem(at: URL(string: "file://" + libPath + file)!)
          } catch {
            NSLog("删除过期mp3失败")
          }
        }
      }
    }
    
    private func now() -> Int {
        return Int(Date().timeIntervalSince1970*1000)
    }
    
}
